#include "stdafx.h"
#include "AutoRelease.h"

using namespace unigame;

AutoRelease* AutoRelease::s_head = 0;
AutoRelease* AutoRelease::s_end = 0;
AutoRelease* AutoRelease::s_deleteEnd = 0;
AutoRelease* AutoRelease::s_deleteHead = 0;
bool AutoRelease::s_isLock = false;

void AutoRelease::clear()
{
	if(s_head == 0)
	{
		return;
	}
	s_isLock = true;
	while(s_head)
	{
		AutoRelease* next = s_head->m_next;
		if(s_head->m_referenceCount <= 0)
		{
			delete s_head;
		}
		else
		{
			s_head->m_next = 0;
		}
		if(s_head == next)
		{
			break;
		}
		s_head = next;
	}
	s_head = s_deleteHead;
	s_end = s_deleteEnd;
	s_deleteHead = 0;
	s_deleteEnd = 0;
	s_isLock = false;
}

void AutoRelease::addToDestroy()
{
	if(s_isLock)
	{
		if(s_deleteEnd == 0)
		{
			s_deleteHead = s_deleteEnd = this;
		}
		else
		{
			s_deleteEnd->m_next = this;
			s_deleteEnd = this;
		}
	}
	else
	{
		if(s_end == 0)
		{
			s_head = s_end = this;
		}
		else
		{
			s_end->m_next = this;
			s_end = this;
		}
	}
	m_next = this;
}